package com.king.juc.shared;

import lombok.extern.slf4j.Slf4j;

/**
 * @author king
 * @date 2020/10/26 13:30
 */
@Slf4j(topic = "c.sharedDemo")
public class sharedDemo {
    private static Integer counter = 0;
    private static Object lock = new Object();
    public static void main(String[] args) throws InterruptedException {
//        threadSafe();
//        synchronizedDemo();
        synchronizedDemo2();
    }

    /**
     * 线程安全问题
     *      多个对象操作一个静态变量导致结果异常
     */
    public static void threadSafe() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                counter++;
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                counter--;
            }
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.info("{}", counter);
    }

    /**
     * synchronized 对象锁基本使用(面向过程)
     *      用对象锁保证了临界区内代码的原子性, 临界区内的代码对外是不可分割的, 不会被线程切换所打断
     */
    public static void synchronizedDemo() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (lock) {
                    counter++;
                }
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (lock) {
                    counter++;
                }
            }
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.info("{}", counter);
    }

    /**
     * synchronized 对象锁基本使用(面向对象)
     */
    public static void synchronizedDemo2() throws InterruptedException {
        Room room = new Room();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                room.increment();
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                room.decrement();
            }
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.info("{}", room.getCounter());
    }
}
